package com.yuantu.judiciary.serviceimpl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.BankcardExtInfo;
import com.alipay.api.domain.Participant;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.easysdk.base.oauth.models.AlipaySystemOauthTokenResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.member.identification.models.*;
import com.alipay.easysdk.payment.common.models.AlipayTradeCreateResponse;
import com.alipay.easysdk.util.generic.models.AlipayOpenApiGenericResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yuantu.judiciary.dao.IQueryRecordDao;
import com.yuantu.judiciary.dao.IVipInfoDao;
import com.yuantu.judiciary.dao.IVipOrderDao;
import com.yuantu.judiciary.dao.IVipRecordAppletDao;
import com.yuantu.judiciary.model.api_ali.AlipayUserInfoShareResponseDTO;
import com.yuantu.judiciary.model.domain.VipInfoDO;
import com.yuantu.judiciary.model.domain.VipOrderDO;
import com.yuantu.judiciary.model.domain.VipRecordAppletDO;
import com.yuantu.judiciary.model.dto.AddOrderDTO;
import com.yuantu.judiciary.model.enums.AuthResultType;
import com.yuantu.judiciary.model.enums.EndpointType;
import com.yuantu.judiciary.model.enums.OrganizationType;
import com.yuantu.judiciary.model.enums.PayState;
import com.yuantu.judiciary.service.IAgentService;
import com.yuantu.judiciary.service.IApiAliAppletService;
import com.yuantu.judiciary.service.IQueryRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.*;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
@Slf4j
public class AgentServiceImpl implements IAgentService {

    private final IVipRecordAppletDao vipRecordAppletDao;
    private final IVipInfoDao vipInfoDao;
    private final IVipOrderDao vipOrderDao;
    private final IQueryRecordDao queryRecordDao;
    /**
     * 获取H5已使用次数
     * @param accountId
     * @return
     */
    @Override
    public Integer getSearchTimesApplet(Long accountId) {
        Integer searchTimesApplet = 0;
        VipRecordAppletDO vipRecordAppletDO = vipRecordAppletDao.findDistinctByAccountIdAndDeletedFalse(accountId);
        if(!ObjectUtils.isEmpty(vipRecordAppletDO)){
            searchTimesApplet += vipRecordAppletDO.getSearchTimes();
        }
        return searchTimesApplet;
    }

    /**
     * 获取H5可查询次数
     * @param accountId
     * @return
     */
    @Override
    public Integer getSearchTimesH5(Long accountId) {
        List<Long> vipIds = vipInfoDao.findByTypeAndDeletedFalse(OrganizationType.H5).stream()
                .map(VipInfoDO::getId)
                .collect(Collectors.toList());
        List<VipOrderDO> list = vipOrderDao.findAllByCreatorIdAndPayStateAndVipIdInAndDeletedFalse(accountId, PayState.SUCCESS,vipIds);
        return list.stream()
                .mapToInt(VipOrderDO::getSearchTimes)
                .sum();
    }

    @Override
    public Integer getUsedTimesH5(Long accountId){
        List<Long> vipIds = vipInfoDao.findByTypeAndDeletedFalse(OrganizationType.H5).stream()
                .map(VipInfoDO::getId)
                .collect(Collectors.toList());
        return queryRecordDao.getH5QueryRecordCount(
                Collections.singletonList(accountId),
                Arrays.asList(AuthResultType.AUTHORIZED, AuthResultType.SEND_MSG, AuthResultType.AUTHORIZING) ,
                vipIds);

    }

    /**
     * 获取小程序已使用次数
     * @param accountId
     * @return
     */
    public Integer getUsedTimesApplet(Long accountId){
        return queryRecordDao.countDistinctByCreatorIdInAndAuthorizedResultInAndDeletedFalseAndTradeNoIsEmptyOrTradeNoIsNull(
                Collections.singletonList(accountId),
                Arrays.asList(AuthResultType.AUTHORIZED, AuthResultType.SEND_MSG, AuthResultType.AUTHORIZING));

    }

    @Override
    public EndpointType currentUseSearchTimeEndpoint(Long accountId, EndpointType endpointType){
        if(endpointType.equals(EndpointType.APPLET)){
            if(getUsedTimesApplet(accountId) >= getSearchTimesApplet(accountId)) {
                return EndpointType.H5;
            }
        }
        if(endpointType.equals(EndpointType.H5)){
            if(getUsedTimesH5(accountId) >= getSearchTimesH5(accountId)) {
                return EndpointType.APPLET;
            }
        }
        return EndpointType.H5;
    }

    public String getOldestOrderTradeNo(Long accountId) {
        List<Long> vipIds = vipInfoDao.findByTypeAndDeletedFalse(OrganizationType.H5).stream()
                .map(VipInfoDO::getId)
                .collect(Collectors.toList());
        List<VipOrderDO> list = vipOrderDao.findAllByCreatorIdAndPayStateAndVipIdInAndDeletedFalse(accountId,PayState.SUCCESS,vipIds);
        for(VipOrderDO vipOrder:list){
            if(vipOrder.getSearchTimes() == null){
                continue;
            }
            Integer h5OrderUsedTimes = queryRecordDao.countDistinctByTradeNoAndDeletedFalse(vipOrder.getTradeNo());
            if(vipOrder.getSearchTimes() > h5OrderUsedTimes){
                return vipOrder.getTradeNo();
            }
        }
        return null;
    }
}
